import { baseUrl, basicAuthor } from './env';
import axios from 'axios';
import { Message, MessageBox } from 'element-ui';
import {auth} from '../utils';

const getToken = auth.get();

// 创建axios实例
const $axios = axios.create({
  baseURL: baseUrl, // api的base_url
  timeout: 5000 // 请求超时时间
});

// request 拦截器
$axios.interceptors.request.use(config => {
  const token = auth.get();
  //console.log(config);
  if (token && config.url !== '/token') {
    config.headers.Authorization = 'bearer ' + token;
  } else {
    config.headers.Authorization = 'Basic ' + basicAuthor;
  }
  return config;
}, error => {
  // console.log(error);
  Promise.reject({
    Status:-1,
    Message:error.message
  });
});

// response 拦截器
$axios.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错
     */
    const res = response.data;
    if(res.hasOwnProperty('access_token')){
      auth.set(res.access_token);
      return res;
    }
    if (res.hasOwnProperty('Status') && res.Status !== 1) {
      // 5008:非法的token  5012:其他客户端登录了   5014:Token 过期了
      if (res.Status === 20001 || res.Status === 20002) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          location.reload();
        });
      } else {
        Message({
          message: res.Message,
          type: 'error',
          duration: 3 * 1000
        });
      }
      return Promise.reject(res);
    }
    return res.Data;
  },
  error => {
    // console.log(error);
    Message({
      message: '服务器拒绝了你的请求，并抛给你你哥媚眼~',
      type: 'error',
      duration: 3 * 1000
    });
    return Promise.reject({
      Status:-1,
      Message:error.message
    });
  }
);

export default $axios;
